import json
from config.configs import DINGSTOCK_HOST, DINGSTOCK_PORT, GOAT_ERP_HOST, GOAT_ERP_PORT, DESKTOP_PATH, DATA_PATH
import pymongo
import os
import time
import hashlib
from urllib.parse import quote_plus
from tools.funciton import reset_json, read_xlsx_file, read_json_file, write_spu_json_file, remove_null
from config.configs import GOAT_ERP_HOST, GOAT_ERP_PORT, DATA_PATH
import requests
from time import sleep

ding = pymongo.MongoClient(host=DINGSTOCK_HOST, port=DINGSTOCK_PORT, authMechanism='DEFAULT', authSource='admin',
                           directConnection=True)
account = ding.accounting



class DewuSign:
    def __init__(self, app_secret):
        self.app_secret = app_secret

    def calculate_sign(self, key_dict: dict):
        sort_key_list = []
        for k, v in key_dict.items():
            sort_key_list.append(k)
        sort_key_list.sort()
        new_str = ""
        for key in sort_key_list:
            valueStr = quote_plus(str(key_dict.get(key)).replace('[', '').replace(']', '').replace("'", '"'), 'utf-8')
            new_str = new_str + key + "=" + valueStr + "&"
        new_key = new_str[:-1] + self.app_secret
        m = hashlib.md5()
        m.update(new_key.encode('UTF-8'))
        sign = m.hexdigest().upper()
        return [sign, new_str[:-1]]


def get_auth_brand_list():
    """获取得物已授权品牌列表"""
    file = os.path.join(DATA_PATH, 'brand_datas.json')
    reset_json(file)
    a = DewuSign("b98f9550a45748aea41efea2b570313d4c697348624d44698e68f376add4ebb3")
    url = 'https://openapi.dewu.com/dop/api/v2/spu/auth_brand_list'
    header = {"Host": "openapi.dewu.com", "Content-Type": "application/json",
              "Accept-Encoding": "gzip, deflate, br, zstd"}
    param = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "timestamp": int(round(time.time() * 1000))}
    true_param = {"sign": a.calculate_sign(param)[0], "app_key": "1141a607572a4a23b8c6ce1b1cd14fed",
                  "timestamp": int(round(time.time() * 1000))}
    r = requests.post(url=url, headers=header, json=true_param).json()
    s = r['data']['last_id']
    write_spu_json_file(file, r['data']['list'])
    while s > 0:
        sleep(1)
        new_param = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "timestamp": int(round(time.time() * 1000)),
                     "last_id": str(s)}
        new_true_param = {"sign": a.calculate_sign(new_param)[0], "app_key": "1141a607572a4a23b8c6ce1b1cd14fed",
                          "timestamp": int(round(time.time() * 1000)), "last_id": str(s)}
        res = requests.post(url=url, headers=header, json=new_true_param).json()
        s = res['data']['last_id']
        write_spu_json_file(file, res['data']['list'])


def get_dewu_spus(brand_id, category_ids):
    """获取得物spus信息"""
    file = os.path.join(DATA_PATH, 'spu_datas.json')
    reset_json(file)
    a = DewuSign("b98f9550a45748aea41efea2b570313d4c697348624d44698e68f376add4ebb3")
    param_dict = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "brand_id": brand_id, "category_ids": category_ids,
                  "timestamp": int(round(time.time() * 1000))}
    sign, param = a.calculate_sign(param_dict)
    url = f'https://openapi.dewu.com/dop/api/v1/spu/brand_category_spus?sign={sign}&{param}'
    header = {"Host": "openapi.dewu.com", "Content-Type": "application/json",
              "Accept-Encoding": "gzip, deflate, br, zstd"}
    r = requests.get(url=url, headers=header).json()
    s = r['data']['last_id']
    write_spu_json_file(file, r['data']['list'])
    while s > 0:
        new_param_dict = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "brand_id": brand_id, "category_ids": category_ids,
                          "timestamp": int(round(time.time() * 1000)), "last_id": s}
        sign, param = a.calculate_sign(new_param_dict)
        url1 = f'https://openapi.dewu.com/dop/api/v1/spu/brand_category_spus?sign={sign}&{param}'
        res = requests.get(url=url1, headers=header).json()
        s = res['data']['last_id']
        write_spu_json_file(file, res['data']['list'])
    # url = f'https://openapi.dewu.com/dop/api/v1/spu/oversea/brand_category_spus_oversea_sync?sign={a.calculate_sign(param_dict)[0]}&{a.calculate_sign(param_dict)[1]}'
    # header = {"Host": "openapi.dewu.com", "Content-Type": "application/json",
    #           "Accept-Encoding": "gzip, deflate, br, zstd"}
    # r = requests.get(url=url, headers=header).json()
    # s = r['data']['last_id']
    # write_spu_json_file(file, r['data']['list'])
    # while s > 0:
    #     new_param_dict = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "brand_id": brand_id,
    #                       "category_ids": category_ids,
    #                       "timestamp": int(round(time.time() * 1000)), "last_id": s}
    #     sign, param = a.calculate_sign(new_param_dict)
    #     url1 = f'https://openapi.dewu.com/dop/api/v1/spu/oversea/brand_category_spus_oversea_sync?sign={sign}&{param}'
    #     res = requests.get(url=url1, headers=header).json()
    #     s = res['data']['last_id']
    #     write_spu_json_file(file, res['data']['list'])


def dev_add_spu():
    """根据json文件导入货号"""
    spus, skus = [], []
    file = os.path.join(DATA_PATH, 'spu_datas.json')
    datas = read_json_file(file)['items']
    for j in range(len(datas)):
        for i in datas[j]:
            i['spuId'] = i['spu_id']
            i['categoryId'] = i['category_id']
            i['categoryName'] = i['category_name']
            i['brandId'] = i['brand_id']
            i['brandName'] = i['brand_name']
            i['articleNumber'] = i['article_number']
            i['otherNumbers'] = i['other_numbers']
            i['spuLogo'] = i['spu_logo']
            i['authPrice'] = i['auth_price']
            i['platform'] = 'dewu'
            i['createdAt'] = int(round(time.time() * 1000))
            i['updatedAt'] = int(round(time.time() * 1000))
            spus.append(i)
            for z in i['skus']:
                z['spuId'] = i['spu_id']
                z['skuId'] = z['sku_id']
                z['createdAt'] = int(round(time.time() * 1000))
                z['updatedAt'] = int(round(time.time() * 1000))
                z['extraBarcodes'] = z['extra_code']
                z['__v'] = 0
                z['isBlocked'] = False
                skus.append(z)
        for v in spus:
            keys_to_remove = ['spu_properties', 'skus', 'support_cross', 'spu_id', 'category_name', 'category_id',
                              'brand_name', 'brand_id', 'spu_logo', 'other_numbers', 'article_number', 'auth_price']
            for key in keys_to_remove:
                if key in v:
                    del v[key]
        for d in skus:
            keys_to_remove = ['merchant_sku_code', 'other_merchant_sku_codes', 'sku_id', 'extra_code']
            for key in keys_to_remove:
                if key in d:
                    del d[key]
    account.spus.insert_many(spus, ordered=False)
    account.skus.insert_many(skus, ordered=False)


# get_dewu_spus(10347,[1001045, 1001044, 1000275, 1000270, 1000268, 37, 38, 1001176, 1001189, 1002191, 36, 33, 34, 1000276, 1003478, 1000267, 43, 44, 31, 1000596])  # 鞋类category_ids
# get_dewu_spus(439, [4,5,13,1002848,1002662,10,1002849,14,272,7,9,11,12,15,17,1001273,285,23,24,28]) # 服装类category_ids
# dev_add_spu()


# 服饰类categoryIds
clothes_categoryIdList = [2, 3, 4, 1002848, 5, 10, 13, 14, 1002849, 1002662, 1002850, 1002663, 1002606, 7, 12, 9, 15,
                          272, 11, 285, 1001276, 8, 1001273, 1002607, 17, 1002608, 1002610, 1002609, 1000951, 1003628,
                          1002767, 28, 24, 23, 1002769, 1002770, 166, 1002771, 1001274, 27, 1002768, 1002789, 1002793,
                          1002792, 1002791, 1001258, 1003186, 1002775, 1002774, 1002773, 1002772, 1002618, 1002781,
                          1002627, 1002626, 1002625, 1002624, 1002623, 1002622, 1002621, 1002620, 1002619, 1001392,
                          1000624, 1000623, 1000599, 1002779, 1001393, 1000626, 1001262, 1002617, 1002616, 1002615, 295,
                          1002628, 1003182, 1002419, 1002417, 1002416, 1001271, 1001270, 1001269, 1001268, 1002639,
                          1002638, 1002637, 1002636, 1002635, 1002634, 1002633, 1002632, 1002631, 1002630, 1002629, 146,
                          147]

# 鞋类categoryIds
shoes_categoryIdList = [29, 35, 1001189, 155, 37, 36, 1001176, 38, 40, 42, 1000266, 1001046, 1000274, 1000270, 1001044,
                        1000272, 1000273, 1001047, 1000269, 1001045, 1000275, 1000268, 1001202, 1001048, 1000267,
                        1000271, 30, 33, 31, 34, 32, 1003478, 1000530, 1000529, 1000276, 1001178, 1001179, 1001177,
                        1001180, 1001081, 1000915, 1003476, 1000916, 1000596, 1003477, 1001049, 1001052, 1002191,
                        1001050, 1002188, 1002206, 1001053, 1001051, 1002189, 1002190, 1002194, 1002187, 1002195,
                        1002192, 1002193, 292, 1001042, 1000263, 1000262, 44, 1000264, 41, 43, 1001041, 1001043,
                        1000265, 410, 46, 1002454, 1002453, 45, 1002183, 1002181, 1002182, 1003475]

# 配件类categoryIds
fittings_categoryIdList = [92, 1003709, 1003817, 1003718, 1003717, 1003716, 1003715, 1003714, 96, 1001483, 1000075,
                           1000074, 294, 200, 184, 100, 99, 98, 97, 121, 122, 363, 124, 1001131, 1000076, 1000148, 123,
                           1003148, 1003357, 1003358, 141, 368, 310, 293, 142, 101, 157, 1000084, 1000149, 1000083,
                           1000082, 116, 1002364, 1000945, 1000944, 179, 1000081, 1000080, 1000041, 338, 316, 313, 187,
                           120, 102, 1001674, 1000941, 1000079, 1000078, 1000077, 1000040, 299, 156, 180, 1000090,
                           1000089, 1000088, 1000087, 321, 181, 322, 1000150, 1000086, 323, 347, 1000085, 348]


def get_dewu_spus1(brand_id, category_ids):
    """获取得物spus信息"""
    file = os.path.join(DATA_PATH, 'spu_datas.json')
    reset_json(file)
    a = DewuSign("b98f9550a45748aea41efea2b570313d4c697348624d44698e68f376add4ebb3")
    for category_id in category_ids:
        param_dict = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "brand_id": brand_id, "category_ids": category_id,
                      "timestamp": int(round(time.time() * 1000))}
        url = f'https://openapi.dewu.com/dop/api/v1/spu/oversea/brand_category_spus_oversea_sync?sign={a.calculate_sign(param_dict)[0]}&{a.calculate_sign(param_dict)[1]}'
        header = {"Host": "openapi.dewu.com", "Content-Type": "application/json",
                  "Accept-Encoding": "gzip, deflate, br, zstd"}
        r = requests.get(url=url, headers=header).json()
        print(r)
        if r['msg'] == "商家品牌未授权，请联系管理员":
            pass
        elif r['data']['list'] is None:
            pass
        else:
            s = r['data']['last_id']
            write_spu_json_file(file, r['data']['list'])
            while s > 0:
                new_param_dict = {"app_key": "1141a607572a4a23b8c6ce1b1cd14fed", "brand_id": brand_id,
                                  "category_ids": category_id,
                                  "timestamp": int(round(time.time() * 1000)), "last_id": s}
                url1 = f'https://openapi.dewu.com/dop/api/v1/spu/oversea/brand_category_spus_oversea_sync?sign={a.calculate_sign(new_param_dict)[0]}&{a.calculate_sign(new_param_dict)[1]}'
                res = requests.get(url=url1, headers=header).json()
                s = res['data']['last_id']
                write_spu_json_file(file, res['data']['list'])
    remove_null(file)


# get_dewu_spus1(144, [2, 3])
# dev_add_spu()